package com.ruoyi.web.Scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.maode.domain.entity.Part;
import com.ruoyi.maode.domain.entity.PartBatch;
import com.ruoyi.maode.service.PartBatchService;
import com.ruoyi.web.util.QyWx.SendQyWxMsgUtils;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务类
 * @author zhangwenqiang
 */
@Component
public class ScheduledTasks {

    @Autowired
    private TaskService taskService;

    @Value("${qywx.url}")
    private String qywxUrl;

    @Autowired
    private PartBatchService partBatchService;

    /**
     * 每天的17：00执行一次审核结果汇总数据
     */
    @Scheduled(cron = "0 0 17 * * ?")
    public void sendUrgeApprove() {
        List<Task> tasks;
        tasks = taskService.createTaskQuery().list();
        try {
            // 打印查询到的所有待审批完任务信息
            SendQyWxMsgUtils.sendUrgeApprove(String.valueOf(tasks.size()),qywxUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 每天的17：00执行一次审核结果汇总数据
     */
    @Scheduled(cron = "0 0 17 * * ?")
//    @Scheduled(fixedRate = 60000)
    public void sendTotalApprove() {
        // 今天日期
        LocalDate today = LocalDate.now();
        // 00:00:00
        LocalDateTime startOfDay = today.atStartOfDay();
        // 23:59:59
        LocalDateTime endOfDay = today.atTime(23, 59, 59);
        // 统计合格的数量
        Long ok = partBatchService.count(new LambdaQueryWrapper<PartBatch>()
                .eq(PartBatch::getStatus, Constants.CONSTANTS_TWO)
                .eq(PartBatch::getResult, Constants.CONSTANTS_ONE)
                .between(PartBatch::getUpdateTime, startOfDay, endOfDay));
        // 统计不合格的数量
        Long no = partBatchService.count(new LambdaQueryWrapper<PartBatch>()
                .eq(PartBatch::getStatus, Constants.CONSTANTS_TWO)
                .eq(PartBatch::getResult, Constants.CONSTANTS_ZERO)
                .between(PartBatch::getUpdateTime, startOfDay, endOfDay));
        // 统计审核完的总数量
        Long total = ok + no;
        // 推送消息
        try {
            SendQyWxMsgUtils.sendTotalApprove(String.valueOf(total), String.valueOf(ok), String.valueOf(no), qywxUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
